import os
import requests
from jenkins import Jenkins

jenkins_url = "http://10.111.96.208:8080/"
server = Jenkins(jenkins_url, username='Lan', password='yunuser7880794')
job_name = "job/Data_synchronization"


def get_job_info():
    """
    获取指定 Jenkins 任务的相关信息

    Returns:
        tuple: 包含任务 URL 和最后一次构建的编号
    """
    job_info = server.get_info(job_name)
    job_url = job_info['url']
    job_last_number = job_info['lastBuild']['number']
    return job_url, job_last_number


def read_data(file_path):
    """
    从指定文件中读取数据并整理成字典

    Args:
        file_path (str): 文件路径

    Returns:
        dict: 包含各种状态数量的字典
    """
    content = {}
    with open(file_path) as f:
        for line in f.readlines():
            launch_name, num = line.strip('\n').split(' ')
            content[launch_name] = num
    return content


def push_message():
    """
    推送任务执行情况的消息

    此函数首先获取 Jenkins 任务的相关信息和数据文件中的内容，然后整理成消息内容并通过企业微信的 Webhook 发送出去
    """
    job_url, job_last_number = get_job_info()
    report_url = job_url + str(job_last_number) + '/allure'
    file_path = os.path.dirname(os.getcwd()) + '/allure-report/export/prometheusData.txt'
    content = read_data(file_path)
    passed_num = content['launch_status_passed']  # 通过数量
    failed_num = content['launch_status_failed']  # 失败数量
    broken_num = content['launch_status_broken']  # 阻塞数量
    skipped_num = content['launch_status_skipped']  # 跳过数量
    case_num = content['launch_retries_run']  # 总数量

    webhook = "https://oapi.dingtalk.com/robot/send?access_token=4d28cd4ebbce86ef4829a7033b80a29dea50ce51c76b65e0d31649516a664c50"
    content = {
        "msgtype": "text",
        "text": {
            "content": "新云湖任务执行情况:\n运行总数：" + case_num
                       + "\n通过数量：" + passed_num
                       + "\n失败数量：" + failed_num
                       + "\n阻塞数量：" + broken_num
                       + "\n跳过数量：" + skipped_num
                       + "\n构建地址：" + job_url
                       + "\n报告地址：" + report_url
        }
    }
    requests.post(url=webhook, json=content, verify=False)


push_message()
